package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            boolean match = false;

            // 静态资源处理
            List<Mapper.MappedHost> mappedHosts = mapper.getMappedHosts();
            Mapper.MappedHost mappedHost = mappedHosts.get(0);
            List<Mapper.MappedContext> mappedContexts = mappedHost.getMappedContexts();
            for (int i = 0; i < mappedContexts.size(); i++) {
                Mapper.MappedContext mappedContext = mappedContexts.get(i);
                List<Mapper.MappedWrapper> mappedWrappers = mappedContext.getMappedWrappers();
                for (int temp = 0; temp < mappedWrappers.size(); temp++) {
                    Mapper.MappedWrapper mappedWrapper = mappedWrappers.get(temp);
                    String urlPattern = mappedWrapper.getUrlPattern();
                    if (request.getUrl().equals(urlPattern)) {
                        match = true;
                        HttpServlet httpServlet = mappedWrapper.getHttpServlet();
                        httpServlet.service(request, response);
                    }
                }

            }
            if (!match) {
                response.outputHtml(request.getUrl());
            }
            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
